package com.zhike.mobileimsdk.server.utils;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

/**
 * ZK工具类
 */
public class ZkUtil {
    private static ZooKeeper zk;
    private static final String ZK_PATH = "/Chat";
    private static final String BIZ_PATH = "/NettyServer";

    public static Boolean ZK_ENABLE = false;
    public static String ZK_HOST = "127.0.0.1:2181";

    /**
     * 连接zk，并创建相应的节点
     */
    public void connection() throws Exception {

        zk = new ZooKeeper(ZK_HOST, 10000, new Watcher() {
            // 监控所有被触发的事件
            public void process(WatchedEvent event) {

            }
        });
        Stat zkPath = null;
        zkPath = zk.exists(ZK_PATH, false);
        if (zkPath == null) {
            zk.create(ZK_PATH, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                    CreateMode.PERSISTENT);
        }

        Stat bizPath = zk.exists(ZK_PATH + BIZ_PATH, false);
        if (bizPath == null) {
            zk.create(ZK_PATH + BIZ_PATH, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                    CreateMode.PERSISTENT);
        }

    }

    /**
     * 关闭zk连接
     */
    public void disConnection() {
        if (zk != null) {
            try {
                zk.close();
                System.out.println("close zk ok");
                return;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 向zk /Chat/NettyServer注册一个NettyServer节点
     *
     * @param host
     * @param port
     */
    public void registerNettyServerNode(String host, Integer port) {
        String node = NodeUtil.node(host, port);
        try {
            zk.create(ZK_PATH + BIZ_PATH + "/" + node, node.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                    CreateMode.EPHEMERAL);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除server注册的节点
     */
    public void delRegistryInfo() {
        try {
            zk.delete(ZK_PATH + BIZ_PATH + "/" + NodeUtil.thisNode(), 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
